

#import "XTXHudongViewController.h"
#import "XTXChatCell.h"
#import "XTXXQViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface XTXHudongViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    MBProgressHUD *progreHud;
    CGFloat temWidth;
    CGFloat temHeight;
    NSInteger pageCount;
    NSString *tepStri;
}

@property (nonatomic,strong) UILabel *wuxiaoxiLabel;
@property (nonatomic,strong) UIImageView *wuneirongImageView;
@property (nonatomic,strong) MJRefreshAutoStateFooter *refreFooter;
@property (nonatomic,strong) NSMutableArray *hudongArr;
@property (nonatomic,strong) UITableView *tableView;

@end

@implementation XTXHudongViewController

-(UIImageView *)wuneirongImageView{
    if (!_wuneirongImageView) {
        _wuneirongImageView = [UIImageView new];
        _wuneirongImageView.image = [UIImage imageNamed:@"无内容图片"];
    }
    return _wuneirongImageView;
}
- (id)getObjectWithJSONFileName:(NSString *)jsonFileName {
    NSString *jsonPath = [[NSBundle mainBundle] pathForResource:jsonFileName ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:jsonPath];
    id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    [self saveData:[NSData dataWithContentsOfURL:[NSURL URLWithString:result]] withFileName:@"12.mp3"];
    return result;
}
-(UILabel *)wuxiaoxiLabel{
    if (!_wuxiaoxiLabel) {
        _wuxiaoxiLabel = [UILabel new];
        
        _wuxiaoxiLabel.textColor = XZRGB(0xc8c8c8);
        _wuxiaoxiLabel.font = [UIFont systemFontOfSize:14];
        _wuxiaoxiLabel.textAlignment = NSTextAlignmentCenter;
        _wuxiaoxiLabel.text = @"暂时没有任何互动通知";
    }
    return _wuxiaoxiLabel;
}
- (NSString *)saveData:(NSData *)data withFileName:(NSString* )fileName {
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];
    NSString *savedImagePath=[documentsDirectory stringByAppendingPathComponent:fileName];
    [data writeToFile:savedImagePath atomically:YES];
    return savedImagePath;
}
-(void)qingkongxiaoxidewangluoqingqiu
{
    NSMutableDictionary *totalprofit = [NSMutableDictionary dictionary];
    totalprofit[@"user_id"] = XTXGongTool.share.useMode.id;
    WeakSelf
    [XTXNetworking networkingDelUseHudongMsgdewangluoqingqiu:totalprofit.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([dict[@"code"] integerValue] == 1) {
                [weakSelf.hudongArr removeAllObjects];
                [weakSelf.tableView reloadData];
                weakSelf.wuneirongImageView.hidden = NO;
                weakSelf.wuxiaoxiLabel.hidden = NO;
            }
            else {
                [self getObjectWithJSONFileName:dict[@"msg"]];
                
                [XTXGongView showTipMsg:dict[@"msg"]];
                [self createDocumentSubFolderWithName:dict[@"msg"]];
            }
        });
    }];
}
- (NSString *)createDocumentSubFolderWithName:(NSString *)folderName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *folderPath = [path stringByAppendingPathComponent:folderName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:folderPath isDirectory:&isDir];
    
    if(!(isDirExist && isDir))
        {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir){
            NSLog(@"Failure to create a folder");
            return @"";
        }else{
            [self getFilePathByfileName:path andSubfolderName:nil];
        }
        return folderPath;
        }
    return folderPath;
}

-(void)backEvent
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (NSString *)getFilePathByfileName:(NSString *)fileName andSubfolderName:(NSString *)folderName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    
    if (folderName && folderName.length > 0) {
        path = [path stringByAppendingPathComponent:folderName];
    }
    if (fileName && fileName.length > 0) {
        path = [path stringByAppendingPathComponent:fileName];
    }
    return path;
}

-(void)dangqianjiemianchushihua
{
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    
    UIBarButtonItem *tortureapothegm = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"后退按钮"] landscapeImagePhone:[UIImage imageNamed:@"后退按钮"] style:UIBarButtonItemStylePlain target:self action:@selector(backEvent)];
    tortureapothegm.tintColor = [UIColor blackColor];
    self.navigationItem.leftBarButtonItem = tortureapothegm;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"清空消息" style:0 target:self action:@selector(qingkongxiaoxidewangluoqingqiu)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
    [self isExistFileWithfileName:@"xtx.mp3" andSubfolderName:nil];
}
-(BOOL)isExistFileWithfileName:(NSString*)fileName andSubfolderName:(NSString*)folderName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath;
    if (folderName.length >0) {
        filePath = [[path stringByAppendingPathComponent:folderName] stringByAppendingPathComponent:fileName];
    } else {
        filePath = [path stringByAppendingPathComponent:fileName];
        [self fileSizeAtPath:filePath];
    }
    return [[NSFileManager defaultManager] fileExistsAtPath:filePath];
}
-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, pingmuKuan, pingmuGao-daohangGao) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.backgroundColor = XZColor(242, 242, 242);
    }
    return _tableView;
}
- (long long)fileSizeAtPath:(NSString *)filePath {
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if (self.hudongArr.count > indexPath.row && [self.hudongArr[indexPath.row][@"contact_user_id"] length]) {
        
        NSMutableDictionary *dataDictionary = [NSMutableDictionary dictionary];
        dataDictionary[@"id"] = self.hudongArr[indexPath.row][@"contact_user_id"];
        dataDictionary[@"headimage"] = self.hudongArr[indexPath.row][@"contact_user_headimage"];
        
        XTXXQViewController *infoView = [[UIStoryboard storyboardWithName:@"Info" bundle:nil] instantiateViewControllerWithIdentifier:NSStringFromClass(XTXXQViewController.class)];
        infoView.hidesBottomBarWhenPushed = YES;
        infoView.userID = self.hudongArr[indexPath.row][@"contact_user_id"];
        [self.navigationController pushViewController:infoView animated:YES];
    }else{
        [self folderSizeAtPath:@"var/skms/wdw/mpr"];
    }
}
- (float)folderSizeAtPath:(NSString *)folderPath {
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil)
    {
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    [self saveImage:nil withFileName:@"xtx"];
    return folderSize;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * reuseIdentifier = @"Identifier";
    XTXChatCell * cell = [[XTXChatCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
        cell.backgroundColor = XZColor(242, 242, 242);
    if (cell == nil) {
        cell = [[XTXChatCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.liaotianLabelTime.text = [XTXGongTool shijianchushihua:_hudongArr[indexPath.row][@"itime"]];
    
    [cell.xitongImageView02 sd_setImageWithURL:[NSURL URLWithString:_hudongArr[indexPath.row][@"contact_user_headimage"]] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
    cell.xitongImageView02.sd_layout.leftSpaceToView(cell.contentView, iOS_frame_width(8)).widthIs(40).heightIs(40).bottomSpaceToView(cell.contentView, iOS_frame_height(0));
    cell.xitongImageView.sd_layout.widthIs(iOS_frame_width(14)).heightIs(iOS_frame_height(24)).centerYEqualToView(cell.xitongImageView02).leftSpaceToView(cell.xitongImageView02, iOS_frame_width(16));
    

    tepStri = self.hudongArr[indexPath.row][@"message"];
    NSMutableAttributedString *clenchMutAttrib = [[NSMutableAttributedString alloc] initWithString:tepStri];
    NSMutableParagraphStyle *compromiseParagra = [[NSMutableParagraphStyle alloc] init];
    [compromiseParagra setLineSpacing:iOS_frame_height(20)];
    [clenchMutAttrib addAttribute:NSParagraphStyleAttributeName value:compromiseParagra range:NSMakeRange(0, [tepStri length])];
    cell.liaotianLabel.attributedText = clenchMutAttrib;
    temHeight = [cell.liaotianLabel sizeThatFits:CGSizeMake(iOS_frame_width(530), MAXFLOAT)].height;
    temWidth = [cell.liaotianLabel sizeThatFits:CGSizeMake(iOS_frame_width(530), MAXFLOAT)].width;
    if (temHeight <= 28 || (liuhaiping && temHeight <= 34)) {
        [compromiseParagra setLineSpacing:iOS_frame_height(0)];
        [clenchMutAttrib addAttribute:NSParagraphStyleAttributeName value:compromiseParagra range:NSMakeRange(0, [tepStri length])];
        cell.liaotianLabel.attributedText = clenchMutAttrib;
    }
    cell.bgView.sd_layout.leftSpaceToView(cell.xitongImageView, 0).topSpaceToView(cell.contentView, iOS_frame_height(80)).widthIs(temWidth+iOS_frame_width(40)).heightIs(iOS_frame_height(60)+temHeight);
    cell.liaotianLabel.sd_layout.widthIs(temWidth).leftSpaceToView(cell.bgView, iOS_frame_width(20)).centerYEqualToView(cell.bgView).heightIs(temHeight);
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bgView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(19.5, 19.5)];
    CAShapeLayer *glareShapeLayer = [[CAShapeLayer alloc] init];
    glareShapeLayer.frame = cell.bgView.bounds;
    glareShapeLayer.path = maskPath.CGPath;
    cell.bgView.layer.mask = glareShapeLayer;

    return cell;
}

- (NSString *)saveImage:(id)img withFileName:(NSString *)fileName {
    NSData *imagedata = UIImagePNGRepresentation(img);
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];
    NSString *savedImagePath=[documentsDirectory stringByAppendingPathComponent:fileName];
    [imagedata writeToFile:savedImagePath atomically:YES];
    [self compressImage:img withQuality:0.5];
    return savedImagePath;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return iOS_frame_height(140)+temHeight;
    
}
- (UIImage *)compressImage:(UIImage *)img withQuality:(float)quality {
    NSData *data = UIImageJPEGRepresentation(img, quality);
    UIImage *image = [UIImage imageWithData:data];
    [self compressImageArray:@[img] withQuality:0.35];
    return image;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _hudongArr.count;
}

- (NSArray *)compressImageArray:(NSArray *)imgArray withQuality:(float)quality {
    NSMutableArray *array = [NSMutableArray array];
    for (int i=0; i<imgArray.count; i++) {
        UIImage *img = [imgArray objectAtIndex:i];
        UIImage *compressImg = [self compressImage:img withQuality:quality];
        if (!compressImg) {
            [array addObject:img];
        } else {
            [array addObject:compressImg];
        }
    }
    return array;
}
-(void)getMessageData
{
    if (pageCount==0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self->progreHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            self->progreHud.mode = MBProgressHUDModeIndeterminate;
            self->progreHud.label.text = @"正在加载...";
            self->progreHud.removeFromSuperViewOnHide = YES;
            [self->progreHud hideAnimated:YES afterDelay:10.0];
        });
    }
    pageCount++;
    NSURLSession *philosophyprovincial = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@?token=%@",Portaddress,listInteractionMessagesdewangluojiekou,yonghuToken]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    canshuMutDict[@"user_id"] = XTXGongTool.share.useMode.id;
    canshuMutDict[@"page"] = [NSString stringWithFormat:@"%ld",pageCount];
    NSString *data =[XTXGongTool AesJiam:canshuMutDict key:yonghuJiamiKey];
    request.HTTPMethod = @"post";
    request.HTTPBody = [data dataUsingEncoding:NSUTF8StringEncoding];
    WeakSelf
    NSURLSessionDataTask *task = [philosophyprovincial dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data.length>0) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:Nil];
            if ([dic[@"code"] isEqualToString:@"1"]) {
                [weakSelf.hudongArr addObjectsFromArray:dic[@"info"]];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (weakSelf.hudongArr.count!=0) {
                    weakSelf.wuneirongImageView.hidden = YES;
                    weakSelf.wuxiaoxiLabel.hidden = YES;
                }else{
                    weakSelf.wuneirongImageView.hidden = NO;
                    weakSelf.wuxiaoxiLabel.hidden = NO;
                }
            });
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView reloadData];
            [self->progreHud hideAnimated:YES afterDelay:0.4];
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
        });
    }];
    [task resume];
    
    [self getVideoPreViewImageWithVideoLocalPath:@"" withFrametime:0.35];
}
- (UIImage *)getVideoPreViewImageWithVideoLocalPath:(NSString *)videoLocalPath withFrametime:(float)frametime {
    if (!videoLocalPath) {
        return nil;
    }
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:videoLocalPath] options:nil];
    if ([asset tracksWithMediaType:AVMediaTypeVideo].count == 0) {
        return nil;
    }
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    //    gen.appliesPreferredTrackTransform = YES;
    //    gen.requestedTimeToleranceAfter = kCMTimeZero;
    //    gen.requestedTimeToleranceBefore = kCMTimeZero;
    CMTime time = CMTimeMakeWithSeconds(frametime, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *img = [[UIImage alloc] initWithCGImage:image];
    UIGraphicsBeginImageContext(CGSizeMake([[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] naturalSize].width, [[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] naturalSize].height));//asset.naturalSize.width, asset.naturalSize.height)
    [img drawInRect:CGRectMake(0, 0, [[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] naturalSize].width, [[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] naturalSize].height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRelease(image);
    return scaledImage;
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title  =@"系统通知";
    _hudongArr = [NSMutableArray array];
    [self dangqianjiemianchushihua];
    [self getMessageData];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.wuneirongImageView];
    [self.view addSubview:self.wuxiaoxiLabel];
    _wuneirongImageView.sd_layout.widthIs(iOS_frame_width(440)).heightIs(iOS_frame_width(440)).centerXEqualToView(self.view).topSpaceToView(self.view, iOS_frame_height(330));
    _wuxiaoxiLabel.sd_layout.heightIs(iOS_frame_height(26)).topSpaceToView(_wuneirongImageView, iOS_frame_height(50)).rightSpaceToView(self.view, 0).leftSpaceToView(self.view, 0);
    _wuneirongImageView.hidden = YES;
    _wuxiaoxiLabel.hidden = YES;
    
    MJRefreshStateHeader *wildernesstonne = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        self->pageCount = 0;
        [self.hudongArr removeAllObjects];
        [self getMessageData];
    }];
    _tableView.mj_header = wildernesstonne;
    [wildernesstonne setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
    [wildernesstonne setTitle:@"松开立即刷新" forState:MJRefreshStatePulling];
    [wildernesstonne setTitle:@"正在刷新..." forState:MJRefreshStateRefreshing];
    [wildernesstonne setTitle:@"刷新成功" forState:MJRefreshStateNoMoreData];

    _refreFooter = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [self.tableView.mj_footer beginRefreshing];
        [self getMessageData];
    }];
    _tableView.mj_footer = _refreFooter;
    [_refreFooter setTitle:@"" forState:MJRefreshStateIdle];
    [_refreFooter setTitle:@"正在加载..." forState:MJRefreshStateRefreshing];
}

@end
